"""
图的详细信息，包含图的节点边等信息
"""
from flask import Blueprint, request, jsonify
import server.database.sql.graph.detail as db
from server.utils.formatData import format_data
from server.utils.handleFile import file_to_base64, save_base64_as_file

route_graph_detail = Blueprint('graph/detail', __name__)


# 信息获取
# 获取节点和边
@route_graph_detail.route('', methods=['GET'])
def get_detail():
    if request.method == 'GET':
        gid = request.args.get('gid')
        data = db.get_detail(gid)

        if data is None:
            return 'null'
        # 调整格式
        data = format_data(data)
        if data['back_img'] is None:
            data['back_img'] = ''
        elif len(data['back_img']) > 0:
            data['back_img'] = file_to_base64(str(data['back_img']))

        if data['edges'] is None:
            data['edges'] = []

        if data['nodes'] is None:
            data['nodes'] = []

        return jsonify(data)


# 添加图
@route_graph_detail.route('/add', methods=['POST'])
def add_detail():
    if request.method == 'POST':
        gid = request.form.get('gid')
        uid = request.form.get('uid')
        back_img = request.form.get('back_img')
        zoom = request.form.get('zoom')
        center = request.form.get('center')
        canvas_size = request.form.get('canvas_size')
        show_model = request.form.get('show_model')
        nodes = request.form.get('nodes')
        edges = request.form.get('edges')
        if back_img is not None and len(back_img) > 0:
            file_path = uid + '/' + gid + '/'
            img_name = 'background_img' + '.jpg'
            save_base64_as_file(back_img, file_path, img_name)
            back_img = file_path + img_name

        res = str(db.add_detail(gid, back_img, zoom, center, canvas_size, show_model, nodes, edges))

        return res


# 内容更新
@route_graph_detail.route('/update', methods=['POST'])
def update_detail():
    if request.method == 'POST':
        gid = request.form.get('gid')
        uid = request.form.get('uid')
        back_img = request.form.get('back_img')
        zoom = request.form.get('zoom')
        center = request.form.get('center')
        canvas_size = request.form.get('canvas_size')
        show_model = request.form.get('show_model')
        nodes = request.form.get('nodes')
        edges = request.form.get('edges')
        if back_img is not None and len(back_img) > 0:
            file_path = uid + '/' + gid + '/'
            img_name = 'background_img' + '.jpg'
            save_base64_as_file(back_img, file_path, img_name)
            back_img = file_path + img_name

        res = str(db.update_detail(gid, back_img, zoom, center, canvas_size, show_model, nodes, edges))

        return res
